<?php
/**
 * | ---------------------------------------------------------------------------------------------------
 * | ProjectName: mvc
 * | ---------------------------------------------------------------------------------------------------
 * | Author：johnxu <fsyzxz@163.com>
 * | ---------------------------------------------------------------------------------------------------
 * | Home: https://www.xfjpeter.cn
 * | ---------------------------------------------------------------------------------------------------
 * | Data: 201907182019-07-18
 * | ---------------------------------------------------------------------------------------------------
 * | Desc:
 * | ---------------------------------------------------------------------------------------------------
 */

namespace app\admin\controller;

use app\common\model\AdminRole;
use Exception;
use johnxu\tool\Hash;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;

class User extends Base
{
    protected function _initialize()
    {
        parent::_initialize();

        $this->model    = model('admin');
        $this->validate = validate('admin');
    }

    /**
     * 管理员登录
     * @throws Exception
     */
    public function login()
    {
        $params = $this->request->post();
        if (!$this->validate->scene('login')->check($params)) {
            $this->fail(200, 1, (string)$this->validate->getError());
        }

        // 判断账号密码是否存在
        $user = $this->model::get(['username' => $params['username']]);
        if (!$user) {
            $this->fail(200, 1, '账号不存在');
        } elseif (!Hash::check($params['password'], $user->password)) {
            $this->fail(200, 1, '密码错误');
        } elseif ($user->status !== 1) {
            $this->fail(200, 1, '账号被禁用');
        } else {
            // 登录成功
            $returnData          = [
                'username'        => $user->username,
                'nickname'        => $user->nickname,
                'email'           => $user->email,
                'avatar'          => request()->domain() . $user->avatar,
                'phone'           => $user->phone,
                'create_time'     => $user->create_time,
                'last_login_time' => $user->last_login_time,
                'last_login_ip'   => $user->last_login_ip,
            ];
            $returnData['token'] = $this->createJwtToken($returnData);
            // 更新登录时间和ip
            $user->last_login_ip   = request()->ip();
            $user->last_login_time = time();
            $user->save();

            $this->ok(200, $returnData);
        }
    }

    public function index()
    {
        if (!$this->model) {
            $this->model = model($this->request->controller());
        }

        $list  = $this->model->page($this->page, $this->pageSize)->select();
        $total = $this->model->count('*');

        $this->afterIndex($list);

        $this->ok(200, [
            'list'  => $list->hidden(['password']),
            'total' => $total,
        ]);
    }

    /**
     * 添加管理员后续操作
     * @param array $params
     * @throws \think\Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws PDOException
     */
    protected function afterAdd(array &$params)
    {
        // 判断一下用户名是否已经存在了
        if ($this->model->where('username', $params['username'])->where("id!={$params['id']}")->find()) {
            $this->model->where('id', $params['id'])->delete();
            $this->fail(200, 1, '账号已经存在');
        }
        // 修改这条记录的密码
        $this->model->where('id', $params['id'])->update([
            'password'    => Hash::make($params['password']),
            'create_time' => time(),
            'update_time' => time(),
        ]);
        unset($params['password']);

        // 映射该记录的权限规则
        model('AdminRole')->insert([
            'user_id' => $params['id'],
            'role_id' => $params['role_id'],
        ]);
    }

    /**
     * 修改管理员
     * @param int $id
     */
    public function edit(int $id = 0)
    {
        $params = $this->request->post();
        $row    = $this->model->get($id);
        if (!$row) {
            $this->fail(200, 1, '该记录不存在');
        } else {
            $this->validate->rule([
                'username' => 'require|unique:admin,username,' . $row->id,
                'password' => '',
            ]);
            if (!$this->validate->scene('edit')->check($params)) {
                $this->fail(200, 1, (string)$this->validate->getError());
            }
            if (isset($params['password']) && !empty($params['password'])) {
                $params['password'] = Hash::make($params['password']);
            }
            unset($params['last_login_ip'], $params['last_login_time'], $params['is_system'], $params['update_time'], $params['create_time']);
            $flag = $row->save($params);
            if ($flag) {
                AdminRole::where(['user_id' => $id])->setField('role_id', $params['role_id']);
                unset($row['password']);
                $this->ok(200, $row);
            } else {
                $this->fail(200, 1, '保存失败');
            }
        }
    }

    /**
     * 删除管理员
     * @param int $id
     */
    public function del(int $id = 0)
    {
        $row = $this->model::get($id);
        if (!$row) {
            $this->fail(200, 1, '该记录不存在');
        } elseif ($row->is_system == 1) {
            $this->fail(200, 1, '该记录不允许删除');
        } else {
            if ($row->delete()) {
                $this->ok(200, $row);
            } else {
                $this->fail(200, 1, '删除失败');
            }
        }
    }
}